package org.bjf.modules.user.web.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.bjf.cache.CacheNameConfig.LocalCacheEnum;
import org.bjf.cache.CacheNameConfig.RedisCacheEnum;
import org.bjf.exception.ServiceException;
import org.bjf.modules.core.web.core.LoginRequired;
import org.bjf.modules.core.web.core.PageVO;
import org.bjf.modules.sys.enums.Permission;
import org.bjf.modules.user.bean.User;
import org.bjf.modules.user.enums.UserMsgCode;
import org.bjf.modules.user.enums.UserRedisKey;
import org.bjf.modules.user.query.UserQuery;
import org.bjf.modules.user.service.UserService;
import org.bjf.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Permission(resSn = "user", resDesc = "用户管理 ")
@RequestMapping("api")
public class UserController {

  @Autowired
  private UserService userService;
  @Autowired
  private RedisUtil redisUtil;

  @RequestMapping("user/detail")
  @LoginRequired
  public User detail(@RequestParam long userId) {
    if (userId == 12) {
      //异常使用示例
      throw new ServiceException(UserMsgCode.USER_NOT_EXIST);
    }
    // redis使用示例
    redisUtil.setex(UserRedisKey.TOKEN_API.as("xxoo", "bbyy"), "myvalue", 10000);
    return userService.get(userId);
  }

  @RequestMapping("user/list")
  @Cacheable(value = RedisCacheEnum.Names.USER, key = "'live:user:list'", sync = true)
  public List<User> list(UserQuery query) {
    return userService.list(query);
  }

  @RequestMapping("user/listPage")
  @CacheEvict(value = LocalCacheEnum.Names.LOCAL, key = "'live:user:list'")
  public PageVO<User> listPage(UserQuery query) {
    return userService.listPage(query);
  }

  @RequestMapping("user/listAll")
  public List<User> listAll(UserQuery query) {
    return userService.listAll(query);
  }

  @RequestMapping("user/listMap")
  public Object listMap(UserQuery query) {
    Map<Long, User> longUserMap = userService.mapByIds(Arrays.asList(10L, 30L), Long.class);
    return longUserMap;
  }

  @RequestMapping("user/add")
  public void add(@Validated User user) {
    userService.add(user);
  }

  @RequestMapping("user/update")
  public void update(@Validated User user) {
    userService.updateById(user);
  }

  @RequestMapping("user/delete")
  public void delete(long id) {
    userService.deleteById(id);
  }


}
